from machine import Timer, Pin, I2C
from blinker import Device
import time
import json
import random
from aht20 import AHT20
from bmp280 import BMP280

authKey = 'xxxxxxxxxx'
ssid = "xxxxxxxxxx"
password = "xxxxxxxxxx"

my_timer = Timer(-1)# -1 的 ID 构造一个虚拟计时器
btn_123_cnt = 0

# 创建I2C对象
i2c = I2C(scl=Pin(2), sda=Pin(0), freq=100000)  # ESP8266的D1->GPIO5作为SCL, D2->GPIO4作为SDA

# 传感器地址
AHT20_ADDR = 0x38
BMP280_ADDR = 0x77

# 中断回调函数的形参必须要有一个,没有也要添加self作为实参来传递
def timer_callback(self):
    light.dataStore({"t1", random.getrandbits(7)})
    
def sub_callback(topic, message):
    global btn_123_cnt
    
    raw = message.decode()
    print("收到消息:", raw)    
    rcv = json.loads(raw)
    if rcv.get("data").get("get") == "state":
        rssi = light.wifiRssi
        if rssi >= -50:
            signal = "fas fa-signal"
        elif rssi >= -62:
            signal = "fas fa-signal-4"
        elif rssi >= -74:
            signal = "fas fa-signal-3"
        elif rssi >= -82:
            signal = "fas fa-signal-2"
        elif rssi >= -92:
            signal = "fas fa-signal-1"
        else:
            signal = "fas fa-signal-slash"
        
        state = {"state":"online"}
        num_abc = {"num-abc": {"val": rssi, "ico": signal}}
        state.update(num_abc)
        light.send(state)
        print("发送消息:", state)
    elif rcv.get("data").get("btn-3x4") == "on":
        btn = {"btn-3x4": {"swi": "on", "clr": "#EA0909"}}
        light.send(btn)
        print("发送消息:", btn)
#         p2.value(0)
    elif rcv.get("data").get("btn-3x4") == "off":
        btn = {"btn-3x4": {"swi": "off", "clr": "#595959"}}
        light.send(btn)
        print("发送消息:", btn)
#         p2.value(1)
    elif rcv.get("data").get("btn-amj") == "tap":
        btn_123_cnt += 1
        num = {"num-9he": {"val": btn_123_cnt}}
        light.send(num)
        print("发送消息:", num)
    else:
        pass

if __name__ == '__main__':
    light = Device(sub_callback)
    light.begin(authKey,ssid, password)
    
    # 创建BMP280对象
    bmp = BMP280(i2c, BMP280_ADDR)
    
    # 创建AHT20对象
    aht = AHT20(i2c, AHT20_ADDR)
    
    temperature = aht.temperature
    humidity = aht.humidity
    tmp = bmp.temperature
    pressure = bmp.pressure
    at = bmp.get_altitude(1012)
    
    try:
        if light.isconnect == 1:
            my_timer.init(period = 62999,
                      mode = Timer.PERIODIC,
                      callback = timer_callback
                      )
        while True:
            light.run()
            time.sleep_ms(25)
    except KeyboardInterrupt:
        print("\n按下Ctrl + C中断程序...\n")
    finally:
        light.disconnect()
        my_timer.deinit()
